export default class WebsocketTask{
  constructor(url,time){
     this.url = url
     this.data = null
     this.isOpenSocket = false
     // 心跳检测
     this.timeout = time
     this.heartbeat = null
 
     try{
       return this.connectSocketInit()
     }catch(e){
       this.isOpenSocket = false
       this.reconnect();
     } 
  }

  connectSocketInit(){
    this.socketTask = uni.connectSocket({
      url: this.url,
	  header: {
	  	'content-type': 'application/json'
	  },
	  method: 'GET',
	  success: (res) => {
	  	console.log(res, 'success');
	  }
    })
    this.socketTask.onOpen((res)=>{
		 console.log('连接成功!!!')
      clearTimeout(this.heartbeat);
      this.isOpenSocket = true
      this.start();
      this.socketTask.onMessage((res)=>{
         //接收消息
		 console.log('onMessage!!!',res)
      })
    })
	this.socketTask.onError((res)=>{
	   console.log('连接错误',res)
	})

    this.socketTask.onClose(()=>{
      this.isOpenSocket = false;
      this.reconnect();
    })
  }
  onMessage(){
	  this.socketTask.onMessage((res)=>{
	     //接收消息
	  		 // console.log('onMessage!!!',res)
			 return res
	  })
  }
onError(){
	
	
}
  //发送消息
  send(data){
    this.socketTask.send({
       data,
    })
  }
  //开启心跳检测
  start(){
    this.heartbeat = setTimeout(()=>{
       // this.data = {value:'xx'}
       // this.send(JSON.stringify(this.data));
    }, this.timeout)
  }
  // 重新连接
  reconnect(){
   clearInterval(this.heartbeat)
   if(!this.isOpenSocket){
     setTimeout(()=>{
		 console.log('liasidniand')
        this.connectSocketInit();
     }, 3000)
   }
  }
}